/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.TX;

import entity.tx.*;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Randall Chia
 */
@Stateful
public class StakeholderCategorySB implements StakeholderCategorySBRemote {
    @PersistenceContext()
    EntityManager em;

    public String addNewCategory(String description, String type){
        description = description.toLowerCase(); //standardise to lower case
        
        Query q = em.createQuery("SELECT c FROM Category c where LOWER(c.description) = :paramDescp");
        q.setParameter("paramDescp", description);
        List list = q.getResultList(); 
        if(list.isEmpty() == false){
            return "A category of this description already exists";
        }
        
        Category newCategory = new Category();
        
        newCategory.setDescription(description);
        newCategory.setType(type);
        em.persist(newCategory);
        return "Successfully added new stakeholder category.";
    }
    
    
    
    public String removeCategory(String description){
        description.toLowerCase(); //standardise to lower case
        
        Query q = em.createQuery("SELECT c FROM Category c WHERE c.description = :paramDescp");
        q.setParameter("paramDescp", description);
        
        if(q.getResultList().isEmpty()){
            return "The category doesn't exist";
        }
        
        Query q1 = em.createQuery("SELECT c FROM Stakeholder c WHERE c.category.description = :paramDescp");
        q1.setParameter("paramDescp", description);
        if(q1.getResultList().isEmpty()== false){
            return "Category cannot be deleted because there exists some Stakeholders of that category";
        }
                
        for(Object o : q.getResultList()){
            Category c = (Category) o;
            em.remove(c);
        }
        return "Successfully deleted category.";
    }
    
    
    
    public List<Category> getAllCategories(){
        List<Category> returnList = new ArrayList<Category>();
        
        Query q = em.createQuery("SELECT c FROM Category c");
        for(Object o : q.getResultList()){
            Category c = (Category) o;
            returnList.add(c);
        }
        return returnList;
    }
    
    
    
    
}
